package com.group01.community.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.group01.community.entity.*;
import com.group01.community.entity.vo.SysRoleVo;
import com.group01.community.mapper.*;
import com.group01.community.service.SysRoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 角色信息表 服务实现类
 * </p>
 *
 * @author guoyuan
 * @since 2025-05-01
 */
@Service
public class SysRoleServiceImpl extends ServiceImpl<SysRoleMapper, SysRole> implements SysRoleService {


    @Autowired
    private SysRoleMapper roleMapper;
    @Autowired
    private SysUserRoleMapper sysUserRoleMapper;
    @Autowired
    private SysRoleMenuMapper sysRoleMenuMapper;
    @Autowired
    private SysRoleDeptMapper sysRoleDeptMapper;
    @Autowired
    private SysUserMapper sysUserMapper;


    @Override
    public List<SysDictData> getAllByStatus(Long dictId) {
        return roleMapper.getAllByStatus(dictId);
    }

    /**
     * 返回角色列表 + 模糊查询（角色名称+权限字符+状态+创建时间）+菜单权限数据
     *
     * @param current
     * @param size
     * @param roleName  角色名称
     * @param roleKey   权限字符
     * @param status    状态
     * @param startTime 创建开始时间
     * @param endTime   创建结束时间
     * @return
     */
    @Override
    public IPage<SysRole> getRoleList(Long current, Long size, String roleName, String roleKey, String status, String startTime, String endTime, String userName) {

        return roleMapper.getRoleList(new Page<>(current, size), roleName, roleKey, status, startTime, endTime, userName);
    }

    @Override
    public IPage<SysRole> getBaseRoleList(Long current, Long size, String roleName, String roleKey, String status, String startTime, String endTime, String userName) {
        return roleMapper.getBaseRoleList(new Page<>(current, size), roleName, roleKey, status, startTime, endTime, userName);
    }

    /**
     * 根据id获取角色的全部权限
     *
     * @return
     */
    @Override
    public List<SysRoleVo> getRolesAllMenu(Long roleId) {
        return roleMapper.getRolesAllMenu(roleId);
    }

    /**
     * 添加角色
     *
     * @param sysRole
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void addRole(SysRole sysRole) {
//        1.添加角色表
        roleMapper.insert(sysRole);

        SysUser user = sysUserMapper.selectOne(new QueryWrapper<SysUser>().eq("user_name", sysRole.getCreateBy()));
        Long userId = user.getUserId();

//          2.添加用户角色关联表
        SysUserRole userRole = new SysUserRole(userId, sysRole.getRoleId());
        sysUserRoleMapper.insert(userRole);

//        3.添加角色 菜单关联表
        Long[] menuIds = sysRole.getMenuIds();
        Long roleId = sysRole.getRoleId();

        for (int i = 0; i < menuIds.length; i++) {
            SysRoleMenu sysRoleMenu = new SysRoleMenu(roleId, menuIds[i]);
            sysRoleMenuMapper.insert(sysRoleMenu);
        }


    }

    /**
     * 修改角色
     *
     * @param sysRole
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void updateRole(SysRole sysRole) {



        // 1. 根据 role_id  先删除 角色菜单表
        sysRoleMenuMapper.deleteById(sysRole.getRoleId());
        //2. 重新添加角色 菜单关联表
        Long[] menuIds = sysRole.getMenuIds();
        Long roleId = sysRole.getRoleId();

        for (int i = 0; i < menuIds.length; i++) {
            SysRoleMenu sysRoleMenu = new SysRoleMenu(roleId, menuIds[i]);
            sysRoleMenuMapper.insert(sysRoleMenu);
        }
        sysRole.setUpdateTime(LocalDateTime.now());
//        3.修改角色表
        roleMapper.updateById(sysRole);

    }

    /**
     * 删除角色
     *
     * @param roleId
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void deleteRole(String roleId) {
        //1.根据id 删除角色表
        //2.根据roleId   删除角色部门关联 删除角色菜单关联 删除 角色用户关联
        roleMapper.deleteById(roleId);
        sysUserRoleMapper.deleteById(roleId);
        sysRoleMenuMapper.deleteById(roleId);
        sysRoleDeptMapper.deleteById(roleId);

    }

    /**
     * 批量删除
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void deleteBatchRole(Integer[] ids) {
        //1.批量删除 角色表
        List<Integer> idsList = Arrays.asList(ids);
        roleMapper.deleteBatchIds(idsList);

        for (int i = 0; i <idsList.size() ; i++) {
            sysUserRoleMapper.deleteById(idsList.get(i));
            sysRoleMenuMapper.deleteById(idsList.get(i));
            sysRoleDeptMapper.deleteById(idsList.get(i));
        }
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void updateRolePow(SysRole sysRole) {
        //1.删除角色部门关联表
        sysRoleDeptMapper.deleteById(sysRole.getRoleId());

        Long[] deptIds = sysRole.getDeptIds();

        for (int i = 0; i <deptIds.length ; i++) {

            SysRoleDept sysRoleDept = new SysRoleDept(sysRole.getRoleId(),deptIds[i]);
sysRoleDeptMapper.insert(sysRoleDept);
        }


    }


}
